package Chap11;

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;

public class IOtest
{
    public static void main(String[] args) throws IOException
    {
        String str1,str4,str3,str5;
        int a = 0,b = 0,c = 0;
        try
        {
            Scanner scan = new Scanner(System.in);
            File file = new File("sort.txt");
            OutputStream outputstream = new FileOutputStream(file);
            BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(outputstream);

            if (!file.exists())
            {
                file.createNewFile();
            }

            System.out.print("Enter some number: ");
            str1 = scan.nextLine();
            StringTokenizer strs = new StringTokenizer(str1," ");
            int length = strs.countTokens();
            int[] str2 = new int[length];

            while (strs.hasMoreTokens())
            {
                for(int y = 0; y < length; y++)
                {
                    String string = strs.nextToken();
                    str2[y] = Integer.parseInt(string);
                }
            }

            str3 = "";
            for(int str : str2)
            {
                str3 += str + "  ";
            }
            System.out.println("排序前：" + str3);
            bufferedoutputstream.write(str3.getBytes());
            bufferedoutputstream.flush();

            Reader reader = new FileReader(file);
            BufferedReader bufferedreader = new BufferedReader(reader);
            StringTokenizer strss = new StringTokenizer(bufferedreader.readLine());

            while(strss.hasMoreTokens())
            {
                str2[c] = Integer.parseInt(strss.nextToken());
                c++;
            }

            sorting(str2);

            str5 = "";
            for(int str : str2)
            {
                str5 += str + "  ";
            }
            System.out.println("排序后：" + str5);
            str4 = "\n" + str5;
            bufferedoutputstream.write(str4.getBytes());
            bufferedoutputstream.flush();
            bufferedoutputstream.close();
        }
        catch (IOException e)
        {
            System.out.println("错误!!!\n" + e.getMessage());
        }
        catch (NumberFormatException e)
        {
            System.out.println("错误!!!\n" + e.getMessage());
        }
    }

    private static void sorting(int[] str)
    {
        for(int i = 0; i <= str.length - 1; i++)
        {
            int temp = str[i];
            for(int j = i + 1; j < str.length; j++)
              if (str[i] > str[j])
              {
                  str[i] = str[j];
                  str[j] = temp;
              }
        }
    }
}
